package com.gree.scmservice.service.saas.impl;

import com.gree.common.entity.ReturnVo;
import com.gree.common.entity.TablePageData;
import com.gree.common.utils.MinIoUtil;
import com.gree.framework.entity.SaasTenant;
import com.gree.framework.entity.SaasTenantAddon;
import com.gree.framework.utils.SecurityUtils;
import com.gree.scmservice.dao.saasDao.SaasCommodityDao;
import com.gree.scmservice.dao.saasDao.SaasOrderDao;
import com.gree.scmservice.dao.saasDao.SaasTenantAddonDao;
import com.gree.scmservice.entity.saas.SaasCommodity;
import com.gree.scmservice.entity.saas.SaasSysOrder;
import com.gree.scmservice.service.saas.SaasOrderService;
import com.gree.scmservice.service.saas.SaasTenantService;
import com.gree.scmservice.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.List;

/**
 * 包路径: com.gree.scmservice.service.saas.impl
 * 项目名: scm-api
 * 创建时间: 2021-07-14 18:58
 * 描述: TODO
 **/
@Service("SaasOrderService")
public class SaasOrderServiceImpl implements SaasOrderService {

    @Autowired
    private SaasOrderDao saasOrderDao;
    @Autowired
    private SaasCommodityDao saasCommodityDao;
    @Autowired
    private SaasTenantService saasTenantService;
    @Autowired
    private SaasTenantAddonDao saasTenantAddonDao;

    private static final String MONTH = "月";
    private static final String WEEK = "周";
    private static final String YEAR = "年";

    @Override
    public int saveOrder(SaasSysOrder saasSysOrder) {
        long  timeNew =  System.currentTimeMillis();
        int randomNum = (int)((Math.random()*9+1)*100000);
        saasSysOrder.setOrder_no(""+timeNew+ randomNum );
        saasSysOrder.setTenantId(SecurityUtils.getUserWithPasswordMode().get("username").toString());
        saasSysOrder.setOutTradeNo(UUIDUtil.getUUID().trim());
        saasSysOrder.setIsDelete(1);
        saasSysOrder.setOrderStatus(1);
        saasSysOrder.setOrderType(1);
        SaasCommodity groupIdCommodity = saasCommodityDao.getGroupIdCommodity(saasSysOrder.getGroupId());
        if (groupIdCommodity!= null) {
            double fee = groupIdCommodity.getFee();
            saasSysOrder.setOrderMoney(BigDecimal.valueOf(fee*saasSysOrder.getGroupPeriodNum()));
        }
        saasSysOrder.setGroupPeriodUnit(groupIdCommodity.getUnit());
        saasSysOrder.setCreate_time(LocalDateTime.now());
        SaasSysOrder insert = saasOrderDao.insertSaasOrder(saasSysOrder);
        return insert != null?1:0;
    }

    @Override
    public int updateOrder(SaasSysOrder saasSysOrder) {
        return saasOrderDao.updateSaasOrder(saasSysOrder);
    }

    @Override
    public TablePageData<SaasSysOrder> selectOrderPage(SaasSysOrder saasSysOrder) {
        TablePageData<SaasSysOrder> saasSysOrderTablePageData = saasOrderDao.selectOrderPage(saasSysOrder);
        return saasSysOrderTablePageData;
    }

    @Override
    public TablePageData<SaasSysOrder> selectOrderPageOnUser(SaasSysOrder saasSysOrder) {
        String tenantId = SecurityUtils.getUserWithPasswordMode().get("username").toString();
        saasSysOrder.setIsDelete(1);
        saasSysOrder.setTenantId(tenantId);
        TablePageData<SaasSysOrder> saasSysOrderTablePageData = saasOrderDao.selectOrderPage(saasSysOrder);
        return saasSysOrderTablePageData;
    }

    @Override
    public SaasSysOrder getOrderNo(String orderNo) {
        SaasSysOrder orderNoIdOrder = saasOrderDao.getOrderNoIdOrder(orderNo);
        return orderNoIdOrder;
    }

    @Override
    public SaasSysOrder getOutTradeNoOrder(String outTradeNo) {
       SaasSysOrder outTradeNoOrder = saasOrderDao.getOutTradeNoOrder(outTradeNo);
       return outTradeNoOrder;
    }

    @Override
    public int getCheckOutTradeNo(String groupId) {
        String tenantid = SecurityUtils.getUserWithPasswordMode().get("username").toString();
        int isDelete = 1;
        int orderStatus = 1;
        List<SaasSysOrder> checkOutTradeNo = saasOrderDao.getCheckOutTradeNo(tenantid, isDelete, orderStatus, groupId);
        return checkOutTradeNo.size()>0?0:1;
    }

    @Override
    public int updateDelOrderById(String orderNo) {
        return saasOrderDao.updateDelOrderById(orderNo);
    }

    @Override
    public int updateDelOrderByIds(String[] orderNos) {
        return saasOrderDao.updateDelOrderByIds(orderNos);
    }

    @Override
    public int updateStatusOrder(String orderNo, int orderStatus) {
        /** 更新订单状态->通过 */
        int i = saasOrderDao.updateStatusOrder(orderNo,orderStatus);
        if (i > 0){
            if(orderStatus == 2) {
                /** 获取订单的商品 */
                SaasSysOrder orderNoIdOrder = saasOrderDao.getOrderNoIdOrder(orderNo);
                String tenantId = orderNoIdOrder.getTenantId();
                String groupId = orderNoIdOrder.getGroupId();
                Long groupPeriodNum = orderNoIdOrder.getGroupPeriodNum();
                SaasCommodity saasCommodity = saasCommodityDao.getGroupIdCommodity(groupId);

                /** 套餐时间期限 */
                LocalDateTime plus = LocalDateTime.now();
                if (WEEK.equals(orderNoIdOrder.getGroupPeriodUnit())) {
                    plus = LocalDateTime.now().plus(groupPeriodNum, ChronoUnit.WEEKS);
                } else if (MONTH.equals(orderNoIdOrder.getGroupPeriodUnit())) {
                    plus = LocalDateTime.now().plus(groupPeriodNum, ChronoUnit.MONTHS);
                } else if (YEAR.equals(orderNoIdOrder.getGroupPeriodUnit())) {
                    plus = LocalDateTime.now().plus(groupPeriodNum, ChronoUnit.YEARS);
                }
                final LocalDateTime expireTime = plus;

                /** 套餐插件 */
                List<String> addons = Arrays.asList(saasCommodity.getAddonArray().split(","));
                if(addons.size() != 0){
                    addons.forEach(addonId -> {
                        SaasTenantAddon saasTenantAddon = new SaasTenantAddon();
                        saasTenantAddon.setTenantId(tenantId);
                        saasTenantAddon.setAddonId(Long.valueOf(addonId));
                        saasTenantAddon.setExpireTime(expireTime);
                        saasTenantAddon.setStatus(0L);
                        saasTenantAddonDao.insertSaasTenantAddon(saasTenantAddon);
                    });
                }

                SaasTenant saasTenant = saasTenantService.fetchSaasTenant(tenantId);
                saasTenant.setGroupId(groupId);
                saasTenant.setExpireTime(plus);
                saasTenantService.updateSaasTenant(saasTenant);

                saasTenantService.toBeTenant(tenantId,10L,"");
            }
            return 1;
        }
        return 0;
    }

    @Override
    public int closeOrder(String orderNo) {
        return saasOrderDao.updateStatusOrder(orderNo,2);
    }

    @Override
    public int updatePayTypeOrder(SaasSysOrder saasSysOrder) {
        SaasSysOrder orderNoIdOrder = saasOrderDao.getOrderNoIdOrder(saasSysOrder.getOrder_no());
        orderNoIdOrder.setPayCert(saasSysOrder.getPayCert());
        orderNoIdOrder.setPayCertex(saasSysOrder.getPayCertex());
        orderNoIdOrder.setPayTime(LocalDateTime.now());
        orderNoIdOrder.setPayType(2);
        return saasOrderDao.updatePayTypeOrder(orderNoIdOrder);
    }

    @Override
    public int delOrderNos(String[] orderNos) {
        return saasOrderDao.delOrderNos(orderNos);
    }

    @Override
    public ReturnVo uploadPayCert(MultipartFile file, String orderNo) {
        String upload = MinIoUtil.upload("saas/order", "gscm", file);
        if(upload!=null){
            saasOrderDao.updateOrderPayCert(orderNo, upload);
            return ReturnVo.success(upload);
        }
        return ReturnVo.error();
    }

    @Override
    public void downloadPayCert(String payCert, HttpServletResponse response) {
        MinIoUtil.download("gscm", payCert, response);
    }
}
